package cn.com.xy.sms.sdk.number;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.json.JSONArray;

import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.NumberInfoManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.service.number.ParseNumberService;
import cn.com.xy.sms.sdk.util.BaseRunnable;
import cn.com.xy.sms.sdk.util.CallBackState;

/* SDK-428 huangzhiqiang 20160603 start */
public class ReparseNumberRunnable extends BaseRunnable {
    private static final int LIMIT = 20;
    private static final Map<Integer, BaseRunnable> MAP_RUNNABLE = new ConcurrentHashMap<Integer, BaseRunnable>();
    
    private int mType = -1;
	
    public static BaseRunnable getInstance(int type) {
        synchronized (ReparseNumberRunnable.class) {
            BaseRunnable runnable = MAP_RUNNABLE.get(type);
            if (runnable == null) {
                runnable = new ReparseNumberRunnable(type);
                MAP_RUNNABLE.put(type, runnable);
            }
            
            return runnable;
        }
    }
    
    private ReparseNumberRunnable(int type) {
        mType = type;
        mExecuteInterval = Constant.MINUTE;
    }

    @Override
    public void setThreadPriority() {
        boolean preferential = (mType == NumberInfoManager.TYPE_REPARSE_NO_NETWORK_NUM_INFO);
        int priority = preferential ? Thread.MIN_PRIORITY + 1 : Thread.MIN_PRIORITY;
        int threadPriority = preferential ? android.os.Process.THREAD_PRIORITY_BACKGROUND
                : android.os.Process.THREAD_PRIORITY_LOWEST;

        Thread.currentThread().setPriority(priority);
        android.os.Process.setThreadPriority(threadPriority);
    }

    @Override
    public void execute() {
        Map<String, String> needReparseNumInfoMap = NumberInfoManager.needReparseNumInfo(mType, LIMIT);
        parseNumberInfoByService(needReparseNumInfoMap);
    }

    protected static void parseNumberInfoByService(Map<String, String> needReparseNumInfoMap) {
        ParseNumberService.parseByService(needReparseNumInfoMap, null, new XyCallBack() {

            @Override
            public void execute(Object... obj) {
                try {
                    int callBackState = (Integer) obj[0];
                    if (callBackState != CallBackState.HAS_DATA) {
                        return;
                    }
                    JSONArray numInfoArr = (JSONArray) obj[2];
                    ParseNumberCache.updateNumCache(numInfoArr);
                } catch (Throwable e) {
                    LogManager.w(Constant.TAG,
                            "ReparseNumberRunnable parseNumberInfoByService error:", e);
                }
            }
        });
    }
}
/* SDK-428 huangzhiqiang 20160603 end */
